package com.kyh.service.sys.impl;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.kyh.service.sys.RoleButtonService;
import com.kyh.sys.entity.RoleButton;
import com.kyh.sys.mapper.RoleButtonMapper;
import com.kyh.vo.BootstrapTableVoJA;
import com.kyh.vo.R;

@Service("roleButtonService")
public class RoleButtonServiceImpl implements RoleButtonService {

	@Autowired
	private RoleButtonMapper roleButtonMapper;

	@Override
	@Transactional
	public R add(RoleButton entity) throws Exception {
		
		Long roleId = entity.getRoleId();
		Long buttonId = entity.getButtonId();
		// 验证数据是否已存在
		RoleButton roleButtonCheck = roleButtonMapper.getByUk(roleId, buttonId);
		if (roleButtonCheck != null) {
			return R.error("该按钮已授权");
		}
		
		// 添加数据
		if (roleButtonMapper.insert(entity) != 1) {
			throw new RuntimeException("失败");
		}
		
		return R.ok();
	}

	@Override
	@Transactional
	public R deleteTrueByUk(
			Long roleId,
			Long buttonId
			) {
		
		// 验证数据是否已存在
		RoleButton roleButtonCheck = roleButtonMapper.getByUk(roleId, buttonId);
		if (roleButtonCheck == null) {
			return R.error("该按钮尚未授权");
		}
		
		roleButtonMapper.deleteByUk(roleId, buttonId);
		
		return R.ok();
	}

	@Override
	@Transactional
	public R edit(RoleButton entity) throws Exception {
		
		// 更新数据
		if (roleButtonMapper.update(entity) != 1) {
			throw new RuntimeException("失败");
		}
		
		return R.ok();
	}

	@Override
	@Transactional
	public R deleteFalse(Long roleButtonId) throws Exception {
		
		if (roleButtonMapper.deleteFalse(roleButtonId) != 1) {
			throw new RuntimeException("失败");
		}
		
		return R.ok();
	}

	@Override
	public BootstrapTableVoJA search(RoleButton cond) {
		
		List<Map<String, Object>> listMap = cond.queryMap();
		
		int total = cond.count();
		
        BootstrapTableVoJA vo = new BootstrapTableVoJA();
        vo.setRowsByListMap(listMap);
        vo.setTotal(total);
        
        return vo;
	}
}
